from math import trunc, log
import sys

used = set()
def get_bin(x,n):
    s = ""
    for i in xrange(n):
        s += str(x % 2)
        x = x/2
    return s[::-1]

def print_blif(func, out_file):
    if used.__contains__(func):
        return
    used.add(func)
    n = trunc(log(len(func),2))
        
    if n < 3:
        out_file.write('.model a'+func+'\n')
        out_file.write('.inputs ')
        for i in xrange(n):
            out_file.write('x'+str(i)+' ')
        out_file.write('\n.outputs y\n')
        out_file.write('.names ')
        for i in xrange(n):
            out_file.write('x'+str(i)+' ')
        out_file.write('y\n')
        if not func.find('1') == -1:
            for i in xrange(len(func)):
                if func[i] == '1':
                    out_file.write(get_bin(i, n)+' 1\n')
            out_file.write('.end\n\n')
        else:
            for i in xrange(n):
                out_file.write('-')
            out_file.write(' 0\n.end\n\n')
    else:
        out_file.write('.model a'+func+'\n')
        out_file.write('.inputs ')
        for i in xrange(n):
            out_file.write('x'+str(i)+' ')
        out_file.write('\n.outputs y\n')
        
        out_file.write('.subckt a' + func[:len(func)/2])
        for i in xrange(n-1):
            out_file.write(' x'+str(i)+'=x'+str(i+1))
        out_file.write(' y=j1\n')
        
        out_file.write('.subckt a' + func[len(func)/2:])
        for i in xrange(n-1):
            out_file.write(' x'+str(i)+'=x'+str(i+1))
        out_file.write(' y=j2\n')
        
        out_file.write('.subckt a10 x0=x0 y=z\n')
        out_file.write('.subckt a0001 x0=z x1=j1 y=t1\n')
        out_file.write('.subckt a0001 x0=x0 x1=j2 y=t2\n')
        out_file.write('.subckt a0111 x0=t1 x1=t2 y=y\n')
        out_file.write('.end\n\n')
        
        print_blif(func[:len(func)/2], out_file)
        print_blif(func[len(func)/2:], out_file)
        
if (len(sys.argv) > 1):        
    func = sys.argv[1].strip()
    out_file = open('a'+func+'.blif','w')
    print_blif(func, out_file)
    print_blif('0001', out_file)
    print_blif('0111', out_file)
    print_blif('10', out_file)
    